package api

import (
	"fmt"
	"gitee.com/kevin186/keyauth/apps/menu"

	"gitee.com/kevin186/keyauth/apps/token"

	"gitee.com/kevin186/keyauth/common/utils"
	"github.com/emicklei/go-restful/v3"
	"github.com/infraboard/mcube/http/response"
)

func (h *handler) CreateMenu(r *restful.Request, w *restful.Response) {
	req := menu.NewCreateMenuRequest()

	if err := r.ReadEntity(req); err != nil {
		response.Failed(w.ResponseWriter, err)
		return
	}

	set, err := h.service.CreateMenuRole(r.Request.Context(), req)
	if err != nil {
		response.Failed(w.ResponseWriter, err)
		return
	}

	response.Success(w.ResponseWriter, set)
}

func (h *handler) GetInfo(r *restful.Request, w *restful.Response) {
	// 获取请求头中的Token
	accessToken := utils.GetToken(r.Request)
	// 验证Token
	h.log.Debug("创建validateTokenRequest")
	req := token.NewValidateTokenRequest(accessToken)

	h.log.Debug("开始验证token")
	ins, err := h.tokenService.ValidateToken(r.Request.Context(), req)

	if err != nil {
		h.log.Debug("验证token完成，有报错")
		response.Failed(w.ResponseWriter, err)
		return
	}
	h.log.Debug("验证token完成，没有报错")
	// 正常应该从数据库中（mongo）查询所有menuRole，遍历出所请求的用户有哪些权限
	userName := ins.Data.UserName

	//此处从简
	mr, err := menu.NewMenuRole(menu.NewCreateMenuRequest())
	h.log.Debug("获取menuRole成功")
	if err != nil {
		response.Failed(w.ResponseWriter, err)
		return
	}

	if mr.UserName == userName {
		response.Success(w.ResponseWriter, mr)
	} else {
		response.Failed(w.ResponseWriter, fmt.Errorf("未找到用户"))
		return
	}
}
